package com.hugoo.core.slt;

import com.hugoo.core.util.TL;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.util.Base64;

/**
 *
 * @author Lovelock.Chan
 */
public class Action {

    protected final Log log = LogFactory.getLog(this.getClass());
    protected String _sid;

    public AcFwd exec(HttpServletRequest request, HttpServletResponse response) {
        log.warn("未实现本方法哈，，，说明配置的调用存在问题哈！");
        return null;
    }

    protected boolean checkPara(HttpServletRequest request, HttpServletResponse response) {
        String p$sid = request.getParameter("_sid_");
        if (TL.isEmpty(p$sid)) {
            p$sid = (String) request.getAttribute("_sid_");
            if (TL.isEmpty(p$sid)) {
                writeDataToClient(response, "<script>alert('传入的参数值不完整，请联系管理员！');</script>");
                return false;
            }
        }
        this._sid = p$sid;
        return true;
    }

    protected Map parsePara(HttpServletRequest request) {
        Enumeration<String> pnm = request.getParameterNames();
        Map m = new HashMap();
        //--------------------解决优先级问题（传入参数优先）
        HttpSession session = request.getSession();
        Enumeration<String> an = session.getAttributeNames();
        String rm;
        while (an.hasMoreElements()) {
            rm = an.nextElement();
            m.put(rm.toUpperCase(), session.getAttribute(rm));
        }
        //---------------------
        String k;
        while (pnm.hasMoreElements()) {
            k = pnm.nextElement();
            if (!k.endsWith("[name]") && !k.endsWith("[value]")) {
                m.put(k.toUpperCase(), request.getParameter(k));
            } else {
                if (k.endsWith("[name]")) {
                    int s = TL.parseInt(k.substring(0, k.indexOf("[")));
                    m.put(request.getParameter(k).toUpperCase(), request.getParameter(s + "[value]"));
                }
            }
        }
        String sp = (String) m.get("__SPL_PARA__");
        if (TL.isNotEmpty(sp)) {
            TL.parseParaUpper(sp, m, log);
        }
        
//        m.put("SYSUSER", request.getSession().getAttribute("sysuser"));//存用系统操作用户
        return m;
    }

    /**
     * 写文件至客户端 注：以文件流的方式写出 缺省情况下,tomcat以ISO-8859-1输出header，
     * IE不支持filename的RFC2047编码，只有用GBK输出，用URL.encode来对filename编码，才能让IE正常显示中文,并且用IE下载时打开的文件名是正常的
     * 对于非IE的agent,采用RFC2047编码，这样浏览器可以自动识别文件名字符集
     *
     *
     * @param response
     */
    protected void writeDataToClient(HttpServletRequest request, HttpServletResponse response, File tmpFile, String name) {
        response.setContentType("application/OCTET-STREAM");
        try {
            String Agent = request.getHeader("User-Agent").toLowerCase();
            log.info("正准备下载【" + name + "】数据，客户端信息：" + Agent);
            if (Agent.contains("msie") || (Agent.contains("trident/") && Agent.contains("rv:"))) {//解决IE11不能正常识别的问题
                name = new String(name.getBytes("GBK"), "ISO-8859-1");
            } else {
                // 对于非IE的agent,采用RFC2047编码，这样浏览器可以自动识别文件名字符集  
                name = "=?UTF-8?B?" + new String(Base64.encodeBase64(name.getBytes("UTF-8"))) + "?=";
            }
        } catch (UnsupportedEncodingException e) {
            name = UUID.randomUUID().toString();
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
        response.addHeader("Content-Length", "" + tmpFile.length());
        OutputStream os = null;
        FileInputStream is = null;
        try {
            os = response.getOutputStream();
            is = new FileInputStream(tmpFile);
            byte[] b = new byte[4096];
            int i;
            while ((i = is.read(b)) > 0) {
                os.write(b, 0, i);
            }
            os.flush();
        } catch (SocketException e) {
            log.info("客户端取消数据的接收！");
        } catch (IOException e) {
            log.warn("写出文件至客户端时出现异常[" + e.getMessage() + "]！");
        } finally {
            TL.close(os, is);
            tmpFile.delete();
        }
    }

    protected void writeDataToClient(HttpServletResponse response, String info) {
        response.setContentType("text/html;charset=UTF-8");
        Writer w = null;
        try {
            w = response.getWriter();
            w.write(info);
//            log.info("返回值："+info);
        } catch (SocketException e) {
            log.info("客户端取消数据的接收！");
        } catch (IOException ex) {
            log.warn("发送信息至客户端失败！", ex);
        } finally {
            TL.close(w);
        }
    }
}
